﻿@using RuoVea.ExDto
@using RuoVea.OmiReports
@using RuoVea.OmiReports.Language
@using RuoVea.OmiReports.Attributes
@using RuoVea.OmiReports.Options
@{
    AppConfig Reports = ConfigManages.Config ?? new AppConfig();
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@Html.Raw(RuoVea.OmiReports.Language.i18n.paramReports)</title>
    <link href="~/ruoveaui/xg6rvft8p/avue/index.css" rel="stylesheet" />
    <link href="~/ruoveaui/xg6rvft8p/elementui/index.min.css" rel="stylesheet" />
    <style>.el-input-number--small {width: 100px;line-height: 30px;}.field-editor-container {padding: 10px;}.field-toolbar {margin-bottom: 15px;padding: 10px;background: #f5f7fa;border-radius: 4px;}.required-field {color: #f56c6c;}element.style {margin: -10px 10px;}.empty-state {padding: 40px 0;text-align: center;background: #fafafa;border-radius: 4px;}.collapse-toolbar {margin-bottom: 10px;}.database-dialog {max-width: 1200px;}.el-table .cell {padding: 4px 8px;}.el-table .el-input__inner { border: 1px solid #dcdfe6;}.el-table .el-input.is-disabled .el-input__inner {background-color: #f5f7fa;border-color: #e4e7ed;color: #c0c4cc;}.sql-textarea {font-family: 'Courier New', monospace;font-size: 14px;line-height: 1.4;}.el-table .el-button--mini {margin: 2px;}</style>
</head>
<body>

    <div id="app" v-cloak>
        <avue-crud :data="tableData" :option="option" :permission="hasPermission" :page.sync="pageOption" :table-loading="loading"
                   v-on:refresh-change="refreshChange"
                   v-on:row-save="handleRowSave"
                   v-on:row-update="handleRowUpdate"
                   v-on:row-del="handleRowDel"
                   v-on:search-change="searchChange"
                   v-on:search-reset="resetChange"
                   v-on:on-load="onLoad">

            <template slot="menuLeft">
                <el-button type="primary" @@click="addRow" size="mini" icon="el-icon-plus">
                    {{i18n.t('add')}}
                </el-button>
            </template>
            
            <template slot-scope="{row,index}" slot="menu">
                <el-button type="text" size="small" icon='el-icon-edit' @@click="editRow(row,index)">
                    {{i18n.t('edit')}}
                </el-button>
                <el-button type="text" size="small" icon='el-icon-edit' @@click="handleOpenReport(row)">
                    {{i18n.t('report_preview')}}
                </el-button>
            </template>
        </avue-crud>

        <!-- 添加或修改数据库配置信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="95%" top="5vh">
            <el-form ref="sqlForm" :model="reportSql" :rules="rules" style="margin: -10px -10px;">
                <el-row>
                    <el-col :span="24" style="text-align: right">
                        <el-button size="small" @@click="open = false">
                            {{i18n.t('cancel')}}
                        </el-button>
                        <el-button size="small" @@click="submitForm" type="primary" :loading="saveBtnLoading">
                            {{i18n.t('save')}}
                        </el-button>
                    </el-col>
                </el-row>
                
                <el-form-item prop="querySql">
                    <!-- 基本配置标签页 -->
                    <div>
                        <el-row>
                            <el-col :span="6">
                                <el-form-item :label="i18n.t('name')" prop="sqlName" label-width="100px">
                                    <el-input v-model="reportSql.sqlName" size="small" :placeholder="i18n.t('please_enter') + i18n.t('name')"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item :label="i18n.t('code')" prop="code" label-width="100px">
                                    <el-input v-model="reportSql.code" size="small" :placeholder="i18n.t('please_enter') + i18n.t('code')"></el-input>
                                </el-form-item>
                            </el-col>

                            <el-col :span="6">
                                <el-form-item :label="i18n.t('datasource')" prop="databaseId" label-width="120px">
                                    <el-select v-model="reportSql.databaseId" clearable :placeholder="i18n.t('select_placeholder') + i18n.t('datasource')" size="small">
                                        <el-option v-for="item in databaseList" :key="item.id" :label="item.name" :value="Number(item.id)"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item :label="i18n.t('status')" prop="isEnabled" label-width="100px">
                                    <el-radio-group v-model="reportSql.isEnabled" size="small">
                                        <el-radio-button v-for="item in enabledDicData" :key="item.value" :label="item.value" :value="item.value">
                                            {{ item.label }}
                                        </el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item :label="i18n.t('query_sql')" prop="querySql" label-width="100px">
                                    <el-input type="textarea" v-model="reportSql.querySql" :rows="10" 
                                              :placeholder="i18n.t('please_enter') + i18n.t('query_sql')" 
                                              resize="vertical" 
                                              style="font-family:'Courier New',monospace;font-size:14px;" 
                                              @@input="handleQuerySqlChange"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12" style="line-height:12px;font-size:12px;">
                                <el-alert :title="i18n.t('format_example')" type="info"></el-alert>
                                <el-alert title='(row) =>{if(row.isQuery==1){return `<span style="color:#67c23a;"><i class="el-icon-check" style="margin-right:2px;"></i>是</span>`}else{return`<span style="color:#f56c6c;"><i class="el-icon-close" style="margin-right:2px;"></i>否</span>`}}' type="info"></el-alert>
                                <el-alert title='(row) => { if(row.isQuery == 1){ return `<span style="color: #67c23a; font-weight: bold;">是</span>` }else  { return `<span style="color: #f56c6c; font-weight: bold;">否</span>` } }' type="info"></el-alert>
                                <el-alert title='(row) => { if(row.isQuery == 1){ return `<span style="color: #52c41a;">✔ 是</span>` }else  { return `<span style="color: #ff4d4f;">✘ 否</span>` } }' type="info"></el-alert>
                                <el-alert title=' [{"value":"1","label":"是"},{"value":"0","label":"否"}]' type="info"></el-alert>
                            </el-col>
                        </el-row>
                    </div>
                    
                    <div>
                        <div class="field-editor-container">
                            <!-- 工具栏 -->
                            <div class="field-toolbar">
                                <el-button size="mini" icon="el-icon-menu" @@click="formatSql">
                                    {{i18n.t('format_sql')}}
                                </el-button>
                                <el-button size="mini" icon="el-icon-finished" @@click="resolveSql">
                                    {{i18n.t('parse_fields')}}
                                </el-button>
                                <el-button size="small" icon="el-icon-plus" @@click="addField">
                                    {{i18n.t('add_field')}}
                                </el-button>
                                <el-button size="small" icon="el-icon-delete" @@click="batchDeleteFields" :disabled="selectedFields.length === 0">
                                    {{i18n.t('batch_delete')}}
                                </el-button>
                            </div>
                            
                            <!-- Element UI 表格 -->
                            <el-table :data="reportSqlField"
                                      border
                                      style="width: 100%"
                                      row-key="Id"
                                      max-height="500"
                                      @@selection-change="handleFieldSelectionChange">

                                <!-- 选择列 -->
                                <el-table-column type="selection" width="45" align="center"></el-table-column>

                                <!-- SQL字段 -->
                                <el-table-column prop="sqlField" :label="i18n.t('property')" width="180" align="center">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.sqlField" size="small" 
                                                  :placeholder="i18n.t('please_enter') + i18n.t('property')" 
                                                  @@blur="validateField(scope.row, 'sqlField')"></el-input>
                                    </template>
                                </el-table-column>

                                <!-- 列名称 -->
                                <el-table-column prop="columnName" :label="i18n.t('title')" width="150" align="center">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.columnName" size="small" 
                                                  :placeholder="i18n.t('please_enter') + i18n.t('title')" 
                                                  @@blur="validateField(scope.row, 'columnName')"></el-input>
                                    </template>
                                </el-table-column>

                                <!-- 是否列表字段 -->
                                <el-table-column prop="isList" :label="i18n.t('list_display')" width="90" align="center">
                                    <template slot-scope="scope">
                                        <el-checkbox v-model="scope.row.isList" :true-label="1" :false-label="0"></el-checkbox>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="align" :label="i18n.t('alignment')" width="90" align="center">
                                    <template slot-scope="scope">
                                        <el-select v-model="scope.row.align" size="small" :placeholder="i18n.t('select_placeholder')">
                                            <el-option :label="i18n.t('left')" value="left" selected></el-option>
                                            <el-option :label="i18n.t('center')" value="center"></el-option>
                                            <el-option :label="i18n.t('right')" value="right"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>

                                <el-table-column prop="isExport" :label="i18n.t('exportable')" width="65" align="center">
                                    <template slot-scope="scope">
                                        <el-checkbox v-model="scope.row.isExport" :true-label="1" :false-label="0"></el-checkbox>
                                    </template>
                                </el-table-column>

                                <!-- 是否可排序 -->
                                <el-table-column prop="isSortable" :label="i18n.t('sortable')" width="65" align="center">
                                    <template slot-scope="scope">
                                        <el-checkbox v-model="scope.row.isSortable" :true-label="1" :false-label="0"></el-checkbox>
                                    </template>
                                </el-table-column>
                                
                                <!-- 是否查询字段 -->
                                <el-table-column prop="isQuery" :label="i18n.t('queryable')" width="65" align="center">
                                    <template slot-scope="scope">
                                        <el-checkbox v-model="scope.row.isQuery" :true-label="1" :false-label="0"></el-checkbox>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="isHidden" :label="i18n.t('hidden')" width="50" align="center">
                                    <template slot-scope="scope">
                                        <el-checkbox v-model="scope.row.isHidden" :true-label="1" :false-label="0"></el-checkbox>
                                    </template>
                                </el-table-column>

                                <!-- 显示类型 -->
                                <el-table-column prop="htmlType" :label="i18n.t('query_control')" width="120" align="center">
                                    <template slot-scope="scope">
                                        <el-select v-model="scope.row.htmlType" size="small" :placeholder="i18n.t('select_placeholder')">
                                            <el-option :label="i18n.t('textbox')" value="input"></el-option>
                                            <el-option :label="i18n.t('dropdown')" value="select"></el-option>
                                            <el-option :label="i18n.t('date')" value="datetime"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                
                                <!-- 查询方式 -->
                                <el-table-column prop="queryType" :label="i18n.t('comparison')" width="130" align="center">
                                    <template slot-scope="scope">
                                        <el-select v-model="scope.row.queryType" size="small" :placeholder="i18n.t('select_placeholder')">
                                            <el-option v-for="item in queryTypeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>

                                <!-- 字典类型 -->
                                <el-table-column prop="dictType" :label="i18n.t('query_dict')" width="150" align="center">
                                    <template slot-scope="scope">
                                        <el-select v-model="scope.row.dictType" filterable allow-create clearable default-first-option 
                                                   v-if="scope.row.htmlType && scope.row.htmlType.indexOf('select') != -1" 
                                                   size="small" 
                                                   :placeholder="i18n.t('dict_format_example')">
                                            <el-option v-for="item in dictOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>

                                <!-- 排序 -->
                                <el-table-column prop="ordinalNo" :label="i18n.t('order')" width="120" align="center">
                                    <template slot-scope="scope">
                                        <el-input-number v-model="scope.row.ordinalNo" :min="0" :max="999" size="small" controls-position="right"></el-input-number>
                                    </template>
                                </el-table-column>

                                <el-table-column prop="width" :label="i18n.t('width')" width="120" align="center">
                                    <template slot-scope="scope">
                                        <el-select v-model="scope.row.width" size="small" :placeholder="i18n.t('select_placeholder')">
                                            <el-option v-for="item in widthDict" :label="item.label" :value="item.value"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>

                                <el-table-column prop="isAggregate" :label="i18n.t('total')" width="65" align="center">
                                    <template slot-scope="scope">
                                        <el-checkbox v-if="isNumeric(scope.row.dataType)" v-model="scope.row.isAggregate" :true-label="1" :false-label="0"></el-checkbox>
                                    </template>
                                </el-table-column>

                                <el-table-column prop="formatter" :label="i18n.t('formatting')" width="180" align="center">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.formatter" type="textarea" size="small" :rows="1" 
                                                  :placeholder="i18n.t('please_enter')"></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
    <script src="~/ruoveaui/xg6rvft8p/vue/vue.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/index.i18n.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/index.lang.js"></script>
    <script>
        Vue.prototype.i18n.messages.zhCN = {...Vue.prototype.i18n.messages.zhCN,...{"add":"增加","edit":"修改","report_preview":"报表预览","cancel":"取消","save":"保存","name":"名称","code":"代码","datasource":"所属数据源","status":"状态","query_sql":"查询语句","format_example":"格式化示例","format_sql":"格式化Sql","parse_fields":"解析字段","add_field":"新增字段","batch_delete":"批量删除","property":"属性","title":"标题","list_display":"列表显示","alignment":"对其方式","left":"居左","center":"居中","right":"居右","exportable":"可导出","sortable":"可排序","queryable":"可查询","hidden":"隐藏","query_control":"查询控件","textbox":"文本框","dropdown":"下拉框","date":"日期","comparison":"比较","query_dict":"查询字典","order":"排序","width":"宽度","auto":"自适应","total":"合计","formatting":"格式化","confirm_delete_field":"确定要删除该字段吗？","confirm_batch_delete":"确定要删除选中的 {count} 个字段吗？","delete_success":"删除成功","batch_delete_success":"批量删除成功","save_success":"保存成功","sql_required":"请输入SQL查询语句","sql_formatted":"SQL已格式化","select_datasource_first":"请先选择所属数据源","enter_sql_first":"请先输入SQL","please_enter":"请输入","please_select":"请选择"}};
        Vue.prototype.i18n.messages.en = {...Vue.prototype.i18n.messages.en,...{"add":"Add","edit":"Edit","report_preview":"Report Preview","cancel":"Cancel","save":"Save","name":"Name","code":"Code","datasource":"Data Source","status":"Status","query_sql":"Query SQL","format_example":"Format Example","format_sql":"Format SQL","parse_fields":"Parse Fields","add_field":"Add Field","batch_delete":"Batch Delete","property":"Property","title":"Title","list_display":"List Display","alignment":"Alignment","left":"Left","center":"Center","right":"Right","exportable":"Exportable","sortable":"Sortable","queryable":"Queryable","hidden":"Hidden","query_control":"Query Control","textbox":"Textbox","dropdown":"Dropdown","date":"Date","comparison":"Comparison","query_dict":"Query Dictionary","order":"Order","width":"Width","auto":"Auto","total":"Total","formatting":"Formatting","confirm_delete_field":"Confirm to delete this field?","confirm_batch_delete":"Confirm to delete selected {count} fields?","delete_success":"Delete successful","batch_delete_success":"Batch delete successful","save_success":"Save successful","sql_required":"Please enter SQL query","sql_formatted":"SQL formatted","select_datasource_first":"Please select data source first","enter_sql_first":"Please enter SQL first","please_enter":"Please enter","please_select":"Please select"}};
        Vue.prototype.i18n.messages.fr = {...Vue.prototype.i18n.messages.fr,...{"add":"Ajouter","edit":"Modifier","report_preview":"Aperçu du rapport","cancel":"Annuler","save":"Enregistrer","name":"Nom","code":"Code","datasource":"Source de données","status":"Statut","query_sql":"Requête SQL","format_example":"Exemple de format","format_sql":"Formater SQL","parse_fields":"Analyser les champs","add_field":"Ajouter un champ","batch_delete":"Suppression par lot","property":"Propriété","title":"Titre","list_display":"Affichage liste","alignment":"Alignement","left":"Gauche","center":"Centre","right":"Droite","exportable":"Exportable","sortable":"Triable","queryable":"Interrogeable","hidden":"Caché","query_control":"Contrôle de requête","textbox":"Boîte texte","dropdown":"Menu déroulant","date":"Date","comparison":"Comparaison","query_dict":"Dictionnaire requête","order":"Ordre","width":"Largeur","auto":"Auto","total":"Total","formatting":"Formatage","confirm_delete_field":"Confirmer la suppression de ce champ?","confirm_batch_delete":"Confirmer la suppression de {count} champs sélectionnés?","delete_success":"Suppression réussie","batch_delete_success":"Suppression par lot réussie","save_success":"Enregistrement réussi","sql_required":"Veuillez saisir la requête SQL","sql_formatted":"SQL formaté","select_datasource_first":"Veuillez d'abord sélectionner la source de données","enter_sql_first":"Veuillez d'abord saisir SQL","please_enter":"Veuillez saisir","please_select":"Veuillez sélectionner"}};
        Vue.prototype.i18n.messages.ja = {...Vue.prototype.i18n.messages.ja,...{"add":"追加","edit":"編集","report_preview":"レポートプレビュー","cancel":"キャンセル","save":"保存","name":"名前","code":"コード","datasource":"データソース","status":"状態","query_sql":"クエリSQL","format_example":"フォーマット例","format_sql":"SQLをフォーマット","parse_fields":"フィールド解析","add_field":"フィールド追加","batch_delete":"一括削除","property":"プロパティ","title":"タイトル","list_display":"リスト表示","alignment":"配置","left":"左","center":"中央","right":"右","exportable":"エクスポート可能","sortable":"ソート可能","queryable":"クエリ可能","hidden":"非表示","query_control":"クエリコントロール","textbox":"テキストボックス","dropdown":"ドロップダウン","date":"日付","comparison":"比較","query_dict":"クエリ辞書","order":"順序","width":"幅","auto":"自動","total":"合計","formatting":"フォーマット","confirm_delete_field":"このフィールドを削除しますか？","confirm_batch_delete":"選択した{count}個のフィールドを削除しますか？","delete_success":"削除成功","batch_delete_success":"一括削除成功","save_success":"保存成功","sql_required":"SQLクエリを入力してください","sql_formatted":"SQLフォーマット済み","select_datasource_first":"まずデータソースを選択してください","enter_sql_first":"まずSQLを入力してください","please_enter":"入力してください","please_select":"選択してください"}};
        Vue.prototype.i18n.messages.vi = {...Vue.prototype.i18n.messages.vi,...{"add":"Thêm","edit":"Sửa","report_preview":"Xem trước báo cáo","cancel":"Hủy","save":"Lưu","name":"Tên","code":"Mã","datasource":"Nguồn dữ liệu","status":"Trạng thái","query_sql":"Truy vấn SQL","format_example":"Ví dụ định dạng","format_sql":"Định dạng SQL","parse_fields":"Phân tích trường","add_field":"Thêm trường","batch_delete":"Xóa hàng loạt","property":"Thuộc tính","title":"Tiêu đề","list_display":"Hiển thị danh sách","alignment":"Căn chỉnh","left":"Trái","center":"Giữa","right":"Phải","exportable":"Có thể xuất","sortable":"Có thể sắp xếp","queryable":"Có thể truy vấn","hidden":"Ẩn","query_control":"Điều khiển truy vấn","textbox":"Hộp văn bản","dropdown":"Danh sách thả xuống","date":"Ngày","comparison":"So sánh","query_dict":"Từ điển truy vấn","order":"Thứ tự","width":"Chiều rộng","auto":"Tự động","total":"Tổng","formatting":"Định dạng","confirm_delete_field":"Xác nhận xóa trường này?","confirm_batch_delete":"Xác nhận xóa {count} trường đã chọn?","delete_success":"Xóa thành công","batch_delete_success":"Xóa hàng loạt thành công","save_success":"Lưu thành công","sql_required":"Vui lòng nhập truy vấn SQL","sql_formatted":"SQL đã định dạng","select_datasource_first":"Vui lòng chọn nguồn dữ liệu trước","enter_sql_first":"Vui lòng nhập SQL trước","please_enter":"Vui lòng nhập","please_select":"Vui lòng chọn"}};
        Vue.prototype.i18n.messages.zhTW = {...Vue.prototype.i18n.messages.zhTW,...{"add":"增加","edit":"修改","report_preview":"報表預覽","cancel":"取消","save":"保存","name":"名稱","code":"代碼","datasource":"所屬數據源","status":"狀態","query_sql":"查詢語句","format_example":"格式化示例","format_sql":"格式化Sql","parse_fields":"解析字段","add_field":"新增字段","batch_delete":"批量刪除","property":"屬性","title":"標題","list_display":"列表顯示","alignment":"對其方式","left":"居左","center":"居中","right":"居右","exportable":"可導出","sortable":"可排序","queryable":"可查詢","hidden":"隱藏","query_control":"查詢控件","textbox":"文本框","dropdown":"下拉框","date":"日期","comparison":"比較","query_dict":"查詢字典","order":"排序","width":"寬度","auto":"自適應","total":"合計","formatting":"格式化","confirm_delete_field":"確定要刪除該字段嗎？","confirm_batch_delete":"確定要刪除選中的 {count} 個字段嗎？","delete_success":"刪除成功","batch_delete_success":"批量刪除成功","save_success":"保存成功","sql_required":"請輸入SQL查詢語句","sql_formatted":"SQL已格式化","select_datasource_first":"請先選擇所屬數據源","enter_sql_first":"請先輸入SQL","please_enter":"請輸入","please_select":"請選擇"}};
     </script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/index.min.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/zhCN.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/en.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/fr.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/ja.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/vi.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/elementui/lang/zhTW.js"></script>
    <script>Vue.prototype.$baseURL = "@Reports?.PrefixRoute";</script>
    <script src="~/ruoveaui/xg6rvft8p/vue/axios.min.min.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/vue/vue-i18n.min.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/avue/avue.min.js"></script>
    <script src="~/ruoveaui/xg6rvft8p/avue/avue.min.option.js"></script>
    <script src="/ruoveaui/xg6rvft8p/avue/filesaver.min.js"></script>
    <script src="/ruoveaui/xg6rvft8p/avue/xlsx.full.min.js"></script>
    <script>
        var enabledDicData= [{ label: `${Vue.prototype.i18n.t('enable')}`, value: 1, }, { label: `${Vue.prototype.i18n.t('disable')}`, value: 0, }];
        new Vue({
            el: '#app',
            mixins: [curdMixin],
            data() {
                return {
                    themeV: localStorage.getItem('themeV'),
                    name: "RptSql",
                    pageUrl: `/RptSql/pages`,
                    addUrl: `/RptSql/add`,
                    editUrl: `/RptSql/update`,
                    deleteUrl: `/RptSql/delete`,
                    title: Vue.prototype.i18n.t('edit') ,
                    saveBtnLoading: false,
                    enabledDicData:enabledDicData,
                    formOption: formOption,

                    reportSql: {
                        id: 0,
                        sqlName: '',
                        databaseId: null,
                        querySql: ''
                    },
                    reportUrl: '/rptquery/index?id=',
                    open: false,
                    fileList: [],

                    // 字段配置相关数据
                    reportSqlField: [],
                    selectedFields: [],
                    originalFieldData: {},

                    queryTypeOptions: [
                      { "label": "=", "value": "EQ", },
                      { "label": ">", "value": "GT", },
                      { "label": ">=", "value": "GTE", },
                      { "label": "<", "value": "LT", },
                      { "label": "<=", "value": "LTE", },
                      { "label": "LIKE","value": "LIKE", },
                      { "label": "BETWEEN", "value": "BETWEEN", }
                    ],
                      // 字典信息 - 条件控件引用的字典(全部)
                    dictOptions: [],
                      // 宽度选择字典
                    widthDict: [
                        { label: this.i18n.t('input_placeholder') + this.i18n.t('or') + this.i18n.t('select_placeholder'), value: "0" },
                        { label: this.i18n.t('auto'), value: 0 },
                        { label: "80", value: 80 },
                        { label: "120", value: 120 },
                        { label: "160", value: 160 },
                        { label: "200", value: 200 }
                    ],
                    databaseList: [],

                    rules: {
                        sqlName: [{ 
                            required: true, 
                            trigger: "blur", 
                            message: this.i18n.t('please_enter') + this.i18n.t('name') 
                        }],
                        databaseId: [{ 
                            required: true, 
                            trigger: "change", 
                            message: this.i18n.t('select_datasource_first') 
                        }],
                        querySql: [{ 
                            required: true, 
                            trigger: "blur", 
                            message: this.i18n.t('sql_required') 
                        }]
                    },
                    option: {
                        searchShowBtn: Permissions.avePermission(`RptSql:searchBtn`),
                        refreshBtn: Permissions.avePermission(`RptSql:searchBtn`),
                        menuWidth: '400',
                        rowKey: 'id',
                        searchShow: false,
                        editBtn: false,
                        viewBtn: false,
                        addBtn: false,
                        columnBtn: false,
                        dialogWidth: '60%',
                        dialogCustomClass: 'database-dialog',
                        column: [
                            { 
                                prop: "id", 
                                label: this.i18n.t('primary_key'), 
                                search: false, 
                                hide: true, 
                                type: "number", 
                                display: false, 
                                showColumn: false 
                            },
                            { 
                                prop: "sqlName", 
                                label: this.i18n.t('name'), 
                                search: true, 
                                hide: false, 
                                width: '120', 
                                clearable: true, 
                                rules: [{ 
                                    required: true, 
                                    trigger: "blur", 
                                    message: this.i18n.t('please_enter') + this.i18n.t('name') 
                                }]
                            },
                            { 
                                prop: "databaseId", 
                                label: this.i18n.t('datasource'), 
                                slot: true, 
                                search: true, 
                                hide: false, 
                                width: '120', 
                                type: "select",
                                props: { label: "name", value: "id" }, 
                                dicUrl: (Vue.prototype.$baseURL+"/rptdatabase/connectionOptions"), 
                                rules: [{ 
                                    required: true, 
                                    trigger: "change", 
                                    message: this.i18n.t('select_datasource_first') 
                                }] 
                            },
                            { 
                                prop: "isEnabled", 
                                label: this.i18n.t('status'), 
                                search: false, 
                                hide: false, 
                                value: 0, 
                                type: "radio", 
                                button: true, 
                                dicData: enabledDicData, 
                                width: '80' 
                            },
                            { 
                                prop: "reportLink", 
                                label: this.i18n.t('report_link'), 
                                slot: true, 
                                search: false, 
                                hide: false, 
                                overHidden: true, 
                                formatter: (val) => { 
                                    return this.reportUrl + val.id + "&name=" + val.sqlName; 
                                } 
                            }
                        ]
                    }
                }
            },
            created() {
                this.selectRow = {};
                this.loadDataList ();
                this.loadDatabaseList();
            },
            methods: {
                loadDataList() {
                    this.$http.get("/RptSql/DictList").then(ret => {
                        this.dictOptions = ret;
                    });
                },
                loadDatabaseList() {
                    this.$http.get("/rptdatabase/connectionOptions").then(ret => {
                        this.databaseList = ret;
                    });
                },

                isNumeric(dataType){
                    return ['int', 'long', 'float', 'decimal'].indexOf(dataType) >= 0
                },
                
                formatSql() {
                    if (!this.reportSql.querySql) {
                        this.$message.warning(this.i18n.t('sql_required'));
                        return;
                    }

                    // 简单的SQL格式化
                    let formattedSql = this.reportSql.querySql
                        .replace(/\bSELECT\b/gi, '\nSELECT\n  ')
                        .replace(/\bFROM\b/gi, '\nFROM\n  ')
                        .replace(/\bWHERE\b/gi, '\nWHERE\n  ')
                        .replace(/\bAND\b/gi, '\n  AND ')
                        .replace(/\bOR\b/gi, '\n  OR ')
                        .replace(/\bGROUP BY\b/gi, '\nGROUP BY\n  ')
                        .replace(/\bORDER BY\b/gi, '\nORDER BY\n  ')
                        .replace(/\bHAVING\b/gi, '\nHAVING\n  ')
                        .replace(/\bJOIN\b/gi, '\nJOIN\n  ')
                        .replace(/\bLEFT\b/gi, '\nLEFT ')
                        .replace(/\bRIGHT\b/gi, '\nRIGHT ')
                        .replace(/\bINNER\b/gi, '\nINNER ')
                        .replace(/\bOUTER\b/gi, '\nOUTER ');

                    // 清理多余的空行
                    formattedSql = formattedSql.replace(/\n\s*\n/g, '\n').trim();

                    this.reportSql.querySql = formattedSql;
                    this.$message.success(this.i18n.t('sql_formatted'));
                },

                // SQL 输入变化处理
                handleQuerySqlChange(value) {
                    this.reportSql.querySql = value;
                },
                sortColumn(){
                  //默认排序
                  var index = 0;
                  for(var col in this.reportSqlField){
                    this.reportSqlField[index].ordinalNo=this.$set(this.reportSqlField[index],'ordinalNo', (index + 1) * 10);
                    index++;
                  };
                },
                
                // 解析SQL字段
                resolveSql() {
                    if (!this.reportSql.databaseId) {
                        return this.$message.error(this.i18n.t('select_datasource_first'));
                    } else if (!this.reportSql.querySql) {
                        return this.$message.error(this.i18n.t('enter_sql_first'));
                    }

                        this.$http.post("/RptSql/parseSQLText",this.reportSql).then(ret => {
                            console.log("parseSQLText",ret)
                            this.reportSqlField = ret
                            this.sortColumn()
                        });

                },

                // 格式化列名称（将驼峰命名转换为中文）
                formatColumnName(fieldName) {
                    const nameMap = {
                        'id': 'ID',
                        'name': this.i18n.t('name'),
                        'title': this.i18n.t('title'),
                        'type': this.i18n.t('type'),
                        'status': this.i18n.t('status'),
                        'createTime': this.i18n.t('create_time'),
                        'updateTime': this.i18n.t('update_time'),
                        'createBy': this.i18n.t('creator'),
                        'updateBy': this.i18n.t('updater')
                    };

                    if (nameMap[fieldName.toLowerCase()]) {
                        return nameMap[fieldName.toLowerCase()];
                    }

                    // 简单的驼峰转中文
                    return fieldName.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
                },

                // 字段选择变化
                handleFieldSelectionChange(selection) {
                    this.selectedFields = selection;
                },

                // 添加字段
                addField() {
                    const newField = {
                        SqlField: '',
                        ColumnName: '',
                        DataType: 'string',
                        IsList: '1',
                        IsQuery: '0',
                        QueryType: 'EQ',
                        HtmlType: this.i18n.t('textbox'),
                        DictType: '',
                        OrdinalNo: this.reportSqlField.length + 1,
                        IsHidden: false,
                        IsSortable: false,
                    };
                    this.reportSqlField.push(newField);
                    this.originalFieldData[newField.Id] = { ...newField };
                },


                // 删除字段
                deleteField(row) {
                    this.$confirm(this.i18n.t('confirm_delete_field'), this.i18n.t('warning'), {
                        type: 'warning'
                    }).then(() => {
                        const index = this.reportSqlField.findIndex(item => item.Id === row.Id);
                        if (index !== -1) {
                            this.reportSqlField.splice(index, 1);
                            delete this.originalFieldData[row.Id];
                            this.$message.success(this.i18n.t('delete_success'));
                        }
                    }).catch(() => {});
                },

                // 批量删除字段
                batchDeleteFields() {
                    if (this.selectedFields.length === 0) {
                        this.$message.warning(this.i18n.t('please_select_fields_to_delete'));
                        return;
                    }

                    this.$confirm(this.i18n.t('confirm_batch_delete', { count: this.selectedFields.length }), this.i18n.t('warning'), {
                        type: 'warning'
                    }).then(() => {
                        const idsToDelete = this.selectedFields.map(field => field.Id);
                        this.reportSqlField = this.reportSqlField.filter(field => !idsToDelete.includes(field.Id));
                        idsToDelete.forEach(id => delete this.originalFieldData[id]);
                        this.selectedFields = [];
                        this.$message.success(this.i18n.t('batch_delete_success'));
                    }).catch(() => {});
                },

                // 验证字段
                validateField(row, specificField = null) {
                    if (specificField) {
                        if ((specificField === 'sqlField' || specificField === 'columnName') && !row[specificField]) {
                            this.$message.error(`${specificField === 'sqlField' ? this.i18n.t('property') : this.i18n.t('title')} ${this.i18n.t('cannot_be_empty')}`);
                            return false;
                        }
                        return true;
                    }

                    if (!row.sqlField || !row.sqlField.trim()) {
                        this.$message.error(this.i18n.t('property') + this.i18n.t('cannot_be_empty'));
                        return false;
                    }

                    if (!row.columnName || !row.columnName.trim()) {
                        this.$message.error(this.i18n.t('title') + this.i18n.t('cannot_be_empty'));
                        return false;
                    }
                    return true;
                },

                // 工具函数
                isEmpty(val) {
                    return val === null || val === undefined || val === '';
                },

                // 提交表单
                submitForm() {
                    this.$refs.sqlForm.validate(valid => {
                        if (valid) {
                            const invalidFields = this.reportSqlField.filter(field => !this.validateField(field));
                            if (invalidFields.length > 0) {
                                this.$message.error(this.i18n.t('please_complete_field_config'));
                                return;
                            }

                            this.saveBtnLoading = true;

                            const submitData = {
                               reportSql: this.reportSql,
                                reportSqlField: this.reportSqlField
                            };

                            const url = this.reportSql.id ? this.editUrl : this.addUrl;
                            this.$http.post(url, submitData).then(response => {
                                if(response==true){
                                    this.$message.success(this.i18n.t('save_success'));
                                    this.onLoad(this.pageOption);
                                    this.open = false;
                                }
                                this.saveBtnLoading = false;
                            }).catch(() => {
                                this.saveBtnLoading = false;
                            });
                        }
                    });
                },
                editRow(row,index){
                    this.$http.get("/RptSql/Detail/"+row.id).then(ret => {
                          this.reportSql=ret.reportSql;
                          this.reportSqlField=ret.reportSqlField;
                          this.open = true;
                    });
                },
                handleOpenReport(row) {
                    window.open(Vue.prototype.$baseURL+this.reportUrl + row.id+"&name="+row.sqlName);
                },
                addRow() {
                    this.reportSql = {
                        id: 0,
                        sqlName: '',
                        databaseId: null,
                        querySql: ''
                    };
                    this.reportSqlField = [];
                    this.selectedFields = [];
                    this.originalFieldData = {};
                    this.open = true;
                }
            }
        });
    </script>
</body>
</html>

